import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { useModel } from 'umi';
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import { CpasIcon, DevToolBar, DevGrid, DevGridSearchIpt } from '~/public/cpas-ui';
import { Item } from 'devextreme-react/toolbar';
import { columnss, SumLevelcolumns } from "./SimpleDatas";
import { getReportItemsBasicBalanceCheck, getReportItemsData, getReportItemsSumRef } from "./service";
import { LayoutD } from "~/public/cpas-ui/components-bs/Layout/Layout";
// import { TreeList } from "devextreme-react";
// import { Column } from "devextreme-react/tree-list";
import { moneyFormatCol, nanoid10 } from '@/utils';
import DevTreeList from "~/public/cpas-ui/components-ui/express-components/DevListTree";
import { LoadIndicator } from "devextreme-react";

const ReportDataGrid: React.FC<any> = React.forwardRef((props: any, ref: any) => {

    const { initialState } = useModel('@@initialState');
    const { dbname, zcbfid } = initialState?.curPart as API.CurPart;
    const { data_ID } = props;
    const Tabsdata = [
        { id: '0', name: '资产负债表' },
        { id: '1', name: '利润表' },
    ];
    const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "center" };

    const [ReportData, setReportDataGrid] = useState<any[]>([]);
    const [SumLevelData, setSumLevelData] = useState<any[]>([]);
    const [BalanceCheckData, setBalanceCheckData] = useState<any>([]);
    const [tabsState, setTbsStates] = useState<string>('0');
    const TreeListRef = useRef<any>();
    // const [timeData, setTimeData] = useState<string>('');
    // const [bottomTimeData, setBottomTimeData] = useState<string>('');
    const gridRef = useRef<any>();
    const gridBottomContainerRef = useRef<any>();
    const gridTopContainerRef = useRef<any>();
    const [visiblePopupKey, setVisiblePopupKey] = useState<string>('');

    const [visibleBottomPopupKey, setVisibleBottomPopupKey] = useState<string>('keyGuid999');
    const [isRequestLoad, setIsRequestLoad] = useState<boolean>(false);



    // const changeTime = () => {
    //     setTimeData(`${new Date().getTime()}`);
    // }


    const BalanceCheck = async () => {
        const res = await getReportItemsBasicBalanceCheck({
            dbname,
            Data_ID: data_ID,
        });
        if (res.success) {
            setBalanceCheckData(res.data);
            // changeTime();
        }
    };

    const ReportItemsData = async (tabKey: string = '0') => {
        setSumLevelData([]);
        setReportDataGrid([]);
        setIsRequestLoad(true);
        setVisiblePopupKey(nanoid10());
        const res = await getReportItemsData({
            dbname,
            Data_ID: data_ID,
            ownerReport: tabKey === '0' ? '资产负债表' : '利润表',
        });
        if (res.success) {
            setReportDataGrid(res.data);
            setIsRequestLoad(false);
        } else {
            setReportDataGrid([]);
            setIsRequestLoad(false);
        }
        await BalanceCheck();
    }

    useEffect(() => {
        const resizeObserverBottom = new ResizeObserver(entries => {
            for (let entry of entries) {
                const { contentRect, target } = entry;
                if (target === gridBottomContainerRef.current) {
                    const newHeight = contentRect.height;
                    gridRef.current.instance.option('height', newHeight);
                }

            }
        });

        const resizeObserverTop = new ResizeObserver(entries => {
            for (let entry of entries) {
                const { contentRect, target } = entry;
                if (target === gridTopContainerRef.current) {
                    const newHeight = contentRect.height;
                    TreeListRef.current.instance.option('height', newHeight);
                }

            }
        });
        resizeObserverBottom.observe(gridBottomContainerRef.current);
        resizeObserverTop.observe(gridTopContainerRef.current);
        return () => {
            resizeObserverBottom.disconnect();
            resizeObserverTop.disconnect();
        };
    }, []);

    useEffect(() => {
        if (data_ID) {
            setTbsStates('0');
            ReportItemsData();
        }
    }, [data_ID]);


    useImperativeHandle(ref, () => ({
        TabsState: (tab: string) => {
            setTbsStates(tab);
        },
        TreeListRef: () => {
            return TreeListRef.current
        },
        Refresh: () => {
            TreeListRef.current.instance.clearSelection();
            ReportItemsData();
            // TreeListRef.current.instance.refresh();
            // TreeListRef.current.instance.clearFilter('scrolling');
        },
        scrollToInit: () => {
            // const scrollRef = TreeListRef.current.instance.getScrollable();
            // scrollRef.scrollTo({ left: 0, top: 0 });
        }
    }));

    const changeTabsClick = (r: any) => {
        setTbsStates(r);
        ReportItemsData(r);
    }


    const onCellDblClick = useCallback(async (e: any) => {
        if (e.rowType === "data" && e.data?.GUID) {
            let paramsApiName = '';
            if (e.data.sumLevel) {
                paramsApiName = "account.reportItem.subitemRef.getDataList";
            } else {
                paramsApiName = "account.reportItem.subjectRef.getDataList";
            }
            setVisibleBottomPopupKey(nanoid10());
            const r = await getReportItemsSumRef(paramsApiName, {
                dbname,
                Data_ID: data_ID,
                FKGUID: e.data.GUID
            });
            if (r.success) {
                setSumLevelData(r.data);
                // setBottomTimeData(`${new Date().getTime()}`);
            }
        }
        return {}
    }, [data_ID, dbname]);

    function topContainer() {
        return (
            <div style={{ height: "calc(100% - 105px)", position: "relative" }}>


                {isRequestLoad && <div style={{
                    position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: "center", justifyContent: "center",
                    opacity: 0.5, zIndex: "99999", background: "#ddd"
                }}>
                    <LoadIndicator id="medium-indicator" height={50} width={50} />
                </div>}
                <div style={{ width: "100%", height: "50px" }}>
                    <AntTabs
                        activeKey={tabsState}
                        onChange={changeTabsClick}
                        className="StatementTab"
                    >
                        {Tabsdata.map((item: any) => {
                            return <AntTabs.Panel
                                tab={item.name}
                                key={item.id}
                            />
                        })}
                    </AntTabs>
                </div>
                <div ref={gridTopContainerRef} style={{ height: 'calc(100% - 10px)' }} >
                    {
                        useMemo(() => {
                            return <DevTreeList.Default
                                className="PublicTreeList devHeadersCenter"
                                ref={TreeListRef}
                                key={visiblePopupKey}
                                // key={`${new Date().getTime()}`}
                                // onInitialized={(e: any) => {
                                //     e.component.pageIndex(0); // 重置页面索引为0
                                // }}
                                dataSource={ReportData}
                                rootValue='0'
                                keyExpr="code"
                                parentIdExpr="pCode"
                                width="100%"
                                scrolling={{
                                    mode: "virtual",
                                    rowRenderingMode: "virtual",
                                    renderAsync: true
                                }}
                                id="GUID"
                                height="100%"
                                // sheetName="报表项目基础数据"
                                // excelName="报表项目基础数据"
                                defaultColumns={columnss}
                                showRowLines={true}
                                showBorders={true}
                                allowColumnReordering={true}
                                columnHidingEnabled={true}
                                columnAutoWidth={true}
                                onCellClick={onCellDblClick}
                            />
                        }, [ReportData, visiblePopupKey])
                    }
                </div>
                <DevToolBar.Default className='FooterItemStyle'>
                    <Item location="before" >
                        <div style={Divstyle}>
                            {
                                BalanceCheckData.map((item: any) => {
                                    let isColorStr = '';
                                    if (item.diffSum === 0) {
                                        isColorStr = "#000";
                                    } else {
                                        isColorStr = "red";
                                    }
                                    return <>
                                        <div style={{ color: `${isColorStr}`, fontSize: "16px" }}>
                                            <span style={{ marginLeft: "10px" }}>
                                                期末 资产总计:
                                                <span style={{ margin: "0px 5px 0px 5px", }}>{moneyFormatCol(item.assetSum)}</span>
                                            </span>
                                            <span style={{ margin: "0px 15px 0px 15px", }}>
                                                负债和股东权益总计:
                                                <span style={{ margin: "0px 5px 0px 5px", }}>{moneyFormatCol(item.otherSum)}</span>
                                            </span>
                                            <span>
                                                &nbsp;差额:<span style={{ margin: "0px 5px 0px 5px", }}>{moneyFormatCol(item.diffSum)}</span>
                                            </span>
                                            {item.otherSum && <span style={{ color: `${item.SYYE === 0 ? "#000" : 'red'}`, }}>{item.SYYE === 0 ? "" : "损益类报表项目存在余额"}</span>}
                                        </div>
                                    </>
                                })
                            }
                        </div>
                    </Item>
                </DevToolBar.Default>

            </div>
        )
    }

    function bottomContainer() {
        return (
            <div ref={gridBottomContainerRef} style={{ marginTop: "10px", height: '100%', width: '100%' }} >
                {
                    useMemo(() => {
                        return <DevGrid.RangeTap
                            ref={gridRef}
                            width="100%"
                            key={visibleBottomPopupKey}
                            height="calc(100% - 10px)"
                            dataSource={SumLevelData}
                            scrolling={{
                                mode: "virtual",
                                rowRenderingMode: "virtual",
                                renderAsync: true
                            }}
                            keyExpr="GUID"
                            defaultColumns={SumLevelcolumns}
                            showBorders={true}
                            showRowLines={true}
                            showColumnLines={true}
                            allowColumnResizing={true}
                            columnResizingMode="widget"
                            paging={{
                                enabled: false
                            }}
                        />
                    }, [SumLevelData, visibleBottomPopupKey])
                }
            </div>
        )
    }

    return (
        <div style={{ width: "100%", height: '100%' }}>
            <LayoutD
                // columnSize="90%"
                columnSize={['80%', '20%']}
                // rowSize={["650px", "700px", "750px"]}
                topSlot={topContainer()}
                bottomSlot={bottomContainer()}
            />
        </div >
    )
});
export default ReportDataGrid;